//签字意见工具
import base from "./base";
import {toJS} from 'mobx';
import {_} from './pcPublic';
import * as VariableKeys from '../constants/variableKey';
import {Toast, Tools} from 'weaver-mobile';
import * as EmSDK from "./emSDK";
import {getLabel} from './common';
import { controlViewPort } from "./formUtil";

const jQuery = window.jQuery;

export const doSignInputChange = (submitParams = {}, variableParams = {}) => {
    const wfOperateStore = base.wfOperateStore;
	const wfLayoutStore = base.wfLayoutStore;
    const wfSignInputStore = base.allStores.wfSignInputStore
    const {changeSubmitParam} = wfOperateStore;
    const {batchControlVariableMap, isForwad} = wfSignInputStore;
    batchControlVariableMap(variableParams);
	wfLayoutStore.existChangeFormData = true;
    if (!isForwad) changeSubmitParam(submitParams);
}

export const getVariableMapVal = (key, defaultvalue = '') => {
    const wfSignInputStore = base.allStores.wfSignInputStore
    const {variableMap} = wfSignInputStore;
    return variableMap.has(key) ? toJS(variableMap.get(key)) : defaultvalue;
}

//校验签字意见并提示
export const verifyRemark = (params = {}) => {
    let {needCheck, src, needPrompt = true, isOnlyVerify = false,actiontype = '',isaffirmance = '0',isaffirmanceSrc,needVeiryRequired = false} = params;
    const {intervenorright} = base.wfGlobalStore.commonParam || {};
    const wfOperateStore = base.wfOperateStore;
    const {ckStore} = base.allStores.wfSignInputStore;

    const {markInfo = {}, changeSubmitParam,isRichText} = wfOperateStore;
    const {isHideInput = '0', isSignMustInput, extendParams = {} } = toJS(markInfo);
    const {wfSignDefaultFontFamily="",wfSignDefaultFontSize=""}=extendParams;

    if(!needVeiryRequired) {
        if(isHideInput != "1" || intervenorright > 0){
            if(!needCheck) needCheck = !(src == 'save' && actiontype == 'requestOperation') || isaffirmance == "1";
            if((isSignMustInput == "1" && needCheck) || (isSignMustInput == '2' && verifyRemarkMustInput(src,actiontype,needCheck,isaffirmanceSrc)))
                needVeiryRequired = true;
        }
    }

    let result = true;
    //验证签字意见必填
    if (isHideInput != "1" || intervenorright > 0) {
        let remark = getVariableMapVal(VariableKeys.SIGN_CONTENT);
        if(isRichText && ckStore.isInited) {
            remark = ckStore.getData();
        }
        if (needVeiryRequired && !remarkCanBeEmpty()) {
            result = checkRemark(remark);
        }
        //添加字体大小和样式
        if(!isOnlyVerify) {
            let _remark = remarkFilter(remark);
            //处理引用
            const remarkQuote = getRemarkQuoteData(_remark);
            changeSubmitParam(remarkQuote);
        }
    }
    if (result === false && needPrompt) {   //直接提示签字意见未填写
        Toast.info(getLabel(500238,'请输入签字意见！'), 1);
       if(window.location.hash.includes('/req/intervenor')) return false;
        const {showSignInput} = base.allStores.wfSignInputStore
        showSignInput();
    }
    if (result && !isOnlyVerify) {
        changeSubmitParam(getSignInfoDatas());
    }
    return result;
}

export const setRemarkTextStyle = (remark) => {
    const {markInfo = {}} = base.wfOperateStore;
    const { extendParams = {} } = toJS(markInfo);
    const {wfSignDefaultFontFamily = "", wfSignDefaultFontSize = ""} = extendParams;
    if(wfSignDefaultFontFamily || wfSignDefaultFontSize){
        const fontFamily = wfSignDefaultFontFamily ? wfSignDefaultFontFamily.split('/')[1] : '';
        const fontSize = wfSignDefaultFontSize ? wfSignDefaultFontSize.split('/')[1] : '';
        const pre = '<div id="ck_rich_text_default_font" style="';
        let style = '';
        if (fontFamily !== '') {
        style += `font-family:${fontFamily};`;
        }
        if (fontSize !== '') {
        style += `font-size:${fontSize};`;
        }
        remark = `${pre}${style}">${remark}</div>`;
    }
    return remark;
}



//签字意见为必填时，意见框无内容，但是有全文批注、手写签批、语音等，跳过必填校验提示
export const remarkCanBeEmpty = (isForward = false)=>{
    let voiceRemark = getVariableMapVal(isForward ? VariableKeys.FORWARD_SIGN_SPEECH_ATTCHMENT_DATAS : VariableKeys.SIGN_SPEECH_ATTCHMENT_DATAS,[]);
    let fullTextRemark = getVariableMapVal(isForward ? VariableKeys.FORWARD_SIGN_FULL_TEXT_ANNOTATION : VariableKeys.SIGN_FULL_TEXT_ANNOTATION,[]);
    let handWrittenRemark = getVariableMapVal(isForward ? VariableKeys.FORWARD_SIGN_HANDWRITTEN : VariableKeys.SIGN_HANDWRITTEN,{});
    let signImageRemark = getVariableMapVal(isForward ? VariableKeys.FORWARD_SIGN_IMAGE : VariableKeys.SIGN_IMAGE,[]);
    let remarkCanBeEmpty=false;
    if(!(signImageRemark.length==0 && voiceRemark.length==0 && fullTextRemark.length==0 && Object.keys(handWrittenRemark).length == 0)){
        remarkCanBeEmpty=true;
    }
    return remarkCanBeEmpty;
}

export const remarkFilter = (remark = '') => {
    let _remark = remark;
    const mobileSignInputRichText  = getExtendParamValue('mobileSignInputRichText');
    if (_remark && !mobileSignInputRichText) {
        _remark = remark.replace(/​/ig, '');
        _remark = _remark.replace(/\r\n/g, "<br>")
        _remark = _remark.replace(/\n/g, '<br>');
    }
    _remark = formatAtInfo(_remark);
    _remark = appendImg(_remark);
    _remark = setRemarkTextStyle(_remark);
    return _remark;
}

//签字意见验证
export const checkRemark = (remarkcontent) => {
    let hasvalue = true;
    if (remarkcontent == null) {
        hasvalue = false;
    } else {
        let _remarkcontent = remarkcontent;
        _remarkcontent = _remarkcontent.replace(/<p>/ig, '').replace(/<\/p>/ig, '').replace(/ /ig, "").replace(/&nbsp;/ig, "").replace(/<br \/>/ig, "");
        _remarkcontent = _remarkcontent.replace(/\\n/ig, "");
        if (_.trim(_remarkcontent).length === 0) {
            hasvalue = false;
        }
    }
    return hasvalue;
}

//加载签字意见中附件
export const getSignInfoDatas = () => {
    const wfOperateStore = base.wfOperateStore;
    const wfSignInputStore = base.allStores.wfSignInputStore
    const {changeSubmitParam} = wfOperateStore;
    const updateParams = {};
    const {isForwad, variableMap} = wfSignInputStore;
    //annexdocinfos
    const annexdocinfoKey = isForwad ? VariableKeys.FORWARD_SIGN_ANNEX_DOC_INFOS : VariableKeys.SIGN_ANNEX_DOC_INFOS;
    const wfReplaceDataKey = isForwad ? VariableKeys.FORWARD_SIGN_WF_REPLACE_DATAS : VariableKeys.SIGN_WF_REPLACE_DATAS;
    const docReplaceDataKey = isForwad ? VariableKeys.FORWARD_SIGN_DOC_REPLACE_DATAS : VariableKeys.SIGN_DOC_REPLACE_DATAS;
    const fulltextannotationKey = isForwad ? VariableKeys.FORWARD_SIGN_FULL_TEXT_ANNOTATION : VariableKeys.SIGN_FULL_TEXT_ANNOTATION;
    const soundResourceDataKey = isForwad ? VariableKeys.FORWARD_SIGN_SPEECH_ATTCHMENT_DATAS : VariableKeys.SIGN_SPEECH_ATTCHMENT_DATAS;
    const remarkLocationKey = isForwad ? VariableKeys.FORWARD_REMARK_LOCATION : VariableKeys.SIGN_REMARK_LOCATION;
    const handlewritingKey = isForwad ? VariableKeys.FORWARD_SIGN_HANDWRITTEN : VariableKeys.SIGN_HANDWRITTEN;

    const annexdocinfos = getVariableMapVal(annexdocinfoKey, []);
    const signworkflowreplacedata = getVariableMapVal(wfReplaceDataKey, []);
    const signdocreplacedata = getVariableMapVal(docReplaceDataKey, []);
    const fulltextannotationdata = getVariableMapVal(fulltextannotationKey, []);
    const soundResourceData = getVariableMapVal(soundResourceDataKey, []);
    const remarkLoactionData = getVariableMapVal(remarkLocationKey, {});
    const handleWrigingData = getVariableMapVal(handlewritingKey, []);

    let annexdocids = [];
    let signworkflowids = [];
    let signdocids = [];
    let soundResourceIds = [];
    let fulltextannotationids = [];

    annexdocinfos.map((item, index) => annexdocids.push(item.fileid));
    signworkflowreplacedata.map((item, index) => signworkflowids.push(item.id));
    signdocreplacedata.map((item, index) => signdocids.push(item.id));
    soundResourceData.map((item) => soundResourceIds.push(item.fileid));
    fulltextannotationdata.map((item) => fulltextannotationids.push(item.fileid));
    
    updateParams['field-annexupload'] = annexdocids.join(',');
    updateParams['signworkflowids'] = signworkflowids.join(',');
    updateParams['signdocids'] = signdocids.join(',');
    //全文批注
    updateParams['fulltextannotation'] = fulltextannotationids.join(',');
    //语音
    updateParams['speechAttachmente9'] = soundResourceIds.join(',');
    //手写签批
    updateParams['handWrittenSign'] = handleWrigingData.fileid;
    //位置
    if (Object.keys(remarkLoactionData).length > 0) {
        const {longitude, latitude, address = ''} = remarkLoactionData;
        updateParams['remarkLocation'] = new Date().getTime() + ',' + longitude + ',' + latitude + ',' + address;
    }
    const clientType = getClientTypeInfo();
    updateParams['clientType'] = clientType;
    return updateParams;
}

//签字意见内容拼接字符串
export const appendRemark = (v = '') => {
    const {wfSignInputStore} = base.allStores;
    const {isForwad,ckStore} = wfSignInputStore;
    const remarkKey = isForwad ? VariableKeys.FORWARD_SIGN_CONTENT : VariableKeys.SIGN_CONTENT;
    let remark = getVariableMapVal(remarkKey, '');
    remark = `${remark}${v}`;
    let updateParams = {};
    updateParams[remarkKey] = remark;
    doSignInputChange(updateParams, updateParams)
    const mobileSignInputRichText  = getExtendParamValue('mobileSignInputRichText');
    if(mobileSignInputRichText) {
        ckStore.setData(convertSpecialChar(remark));
    }
}

export const getExtendParamValue = (key) =>{
    const {wfOperateStore} = base.allStores;
    const {markInfo = {}} = wfOperateStore;
    const signParams = toJS(markInfo);
    const {extendParams = {}} = signParams;
    return extendParams[key] || '';
}

export const formatAtInfo = (remark = '') => {
    const {wfSignInputStore} = base.allStores;
    const {reqOperators = []} = wfSignInputStore;
    if (reqOperators && reqOperators.length > 0) {
        let __remark = remark;
        reqOperators.map((o) => {
            let atreplace = `<a href="/hrm/HrmTab.jsp?_fromURL=HrmResource&id=${o.uid}" atsome="@${o.uid}" contenteditable='false' style="cursor:pointer;text-decoration:none !important;margin-right:8px;color:#2777c1!important" target="_blank">@${o.data}&nbsp;</a>`;
            let r1 = `@${o.data}`;
            r1 = r1.replace(/\(/g,'（').replace(/\)/g,'）');
            let reg = new RegExp(r1, 'g');
            __remark = __remark.replace(reg, atreplace);
        })
        return __remark;
    }
    return remark;
}

export const appendImg = (remark = '') => {
    const {isForwad} = base.allStores.wfSignInputStore;
    const imgDataKey = isForwad ? VariableKeys.FORWARD_SIGN_IMAGE : VariableKeys.SIGN_IMAGE;
    const imgDatas = getVariableMapVal(imgDataKey, []);
    let __remark = remark;
    if (imgDatas.length > 0) {
        imgDatas.map((item) => {
            const imglink = `/weaver/weaver.file.FileDownload?fileid=${item.fileid}&download=1`;
            __remark += `<p><img src='${imglink}' data-imgsrc='${imglink}'/></p>`;
        })
    }
    return __remark;
}

export const appendQuote = (remark = '') => {
    const {isForward} = base.allStores.wfSignInputStore;
    const quoteDataKey = isForward ? VariableKeys.FORWARD_SIGN_REMARK_QUOTE : VariableKeys.SIGN_REMARK_QUOTE;
    let quoteData = getVariableMapVal(quoteDataKey, []);
    let __remark = remark;
    if (quoteData.length > 0) {
        __remark = quoteData.join('') + "\n" + remark;
    }
    return __remark;
}

export const getRemarkQuoteData = (remark = '') => {
    const {variableMap, isForward} = base.allStores.wfSignInputStore;
    const quoteDataKey = isForward ? VariableKeys.FORWARD_SIGN_REMARK_QUOTE : VariableKeys.SIGN_REMARK_QUOTE;
    let quoteData = getVariableMapVal(quoteDataKey, []);
    let remarkquote = {remark, remarkquote: quoteData.join('~~~~@@@@~~~~@@@@@~~~~')};
    return {remark: appendQuote(remark), remarkquote: JSON.stringify(remarkquote)};
}

export const setMetaViewport = (flag) => {
    controlViewPort(flag ? "/req" : "/req/sign");
}

const calculateRatio = () => {
    let ratio = 1.0;
    let screen = window.screen;
    let ua = navigator.userAgent.toLowerCase();
    if (window.devicePixelRatio !== undefined) {
        ratio = window.devicePixelRatio;
    } else if (~ua.indexOf('msie')) {
        if (screen.deviceXDPI && screen.logicalXDPI) {
            ratio = screen.deviceXDPI / screen.logicalXDPI;
        }
    } else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
        ratio = window.outerWidth / window.innerWidth;
    }
    return ratio;
}

//处理签字意见初始化数据
export const formatRemarkInfo = (remarkInfo = {}) => {
    const {remarkLocation = ''} = remarkInfo;
    //位置
    const locationInfoData = getLocationInfoData(remarkLocation);
    if (Object.keys(locationInfoData).length > 0) {
        remarkInfo[VariableKeys.SIGN_REMARK_LOCATION] = locationInfoData;
    }
    return remarkInfo;
}

//位置串转成对象
export const getLocationInfoData = (remarkLocation = '') => {
    let locationInfoData = {};
    if (remarkLocation) {
        const locationInfos = remarkLocation.split(',');

        if (locationInfos.length === 4) {
            locationInfoData['longitude'] = locationInfos[1];
            locationInfoData['latitude'] = locationInfos[2];
            locationInfoData['address'] = locationInfos[3];
        }
        if( locationInfos.length === 3) {
          //来自pc端的位置信息
          locationInfoData['longitude'] = locationInfos[0];
          locationInfoData['latitude'] = locationInfos[1];
          locationInfoData['address'] = locationInfos[2];
        }
    }
    return locationInfoData;
}

//转发带入默认值
export const asyncSignInfo = (isAsync = false) => {
    //判断转发意见信息是否选择了相关内容，如果有则不同步
    const signContent = getVariableMapVal(VariableKeys.FORWARD_SIGN_CONTENT, '');
    if (checkRemark(signContent)) return false;
    if (getVariableMapVal(VariableKeys.FORWARD_SIGN_FULL_TEXT_ANNOTATION, []).length > 0) return false;
    if (getVariableMapVal(VariableKeys.FORWARD_SIGN_SPEECH_ATTCHMENT_DATAS, []).length > 0) return false;
    if (Object.keys(getVariableMapVal(VariableKeys.FORWARD_SIGN_HANDWRITTEN, {})).length > 0) return false;
    if (Object.keys(getVariableMapVal(VariableKeys.FORWARD_REMARK_LOCATION, {})).length > 0) return false;
    if (getVariableMapVal(VariableKeys.FORWARD_SIGN_IMAGE, []).length > 0) return false;
    if (getVariableMapVal(VariableKeys.FORWARD_SIGN_ANNEX_DOC_INFOS, []).length > 0) return false;
    if (getVariableMapVal(VariableKeys.FORWARD_SIGN_WF_REPLACE_DATAS, []).length > 0) return false;
    if (getVariableMapVal(VariableKeys.FORWARD_SIGN_DOC_REPLACE_DATAS, []).length > 0) return false;

    if (isAsync) {
        let updateParams = {};
        updateParams[VariableKeys.FORWARD_SIGN_CONTENT] = getVariableMapVal(VariableKeys.SIGN_CONTENT, '');
        updateParams[VariableKeys.FORWARD_SIGN_FULL_TEXT_ANNOTATION] = getVariableMapVal(VariableKeys.SIGN_FULL_TEXT_ANNOTATION, []);
        updateParams[VariableKeys.FORWARD_SIGN_SPEECH_ATTCHMENT_DATAS] = getVariableMapVal(VariableKeys.SIGN_SPEECH_ATTCHMENT_DATAS, []);
        updateParams[VariableKeys.FORWARD_SIGN_HANDWRITTEN] = getVariableMapVal(VariableKeys.SIGN_HANDWRITTEN, {});
        updateParams[VariableKeys.FORWARD_REMARK_LOCATION] = getVariableMapVal(VariableKeys.SIGN_REMARK_LOCATION, {});
        updateParams[VariableKeys.FORWARD_SIGN_IMAGE] = getVariableMapVal(VariableKeys.SIGN_IMAGE, []);
        updateParams[VariableKeys.FORWARD_SIGN_ANNEX_DOC_INFOS] = getVariableMapVal(VariableKeys.SIGN_ANNEX_DOC_INFOS, []);
        updateParams[VariableKeys.FORWARD_SIGN_WF_REPLACE_DATAS] = getVariableMapVal(VariableKeys.SIGN_WF_REPLACE_DATAS, []);
        updateParams[VariableKeys.FORWARD_SIGN_DOC_REPLACE_DATAS] = getVariableMapVal(VariableKeys.SIGN_DOC_REPLACE_DATAS, []);
        updateParams[VariableKeys.FORWARD_SIGN_REMARK_QUOTE] = getVariableMapVal(VariableKeys.SIGN_REMARK_QUOTE, []);
        const {batchControlVariableMap} = base.allStores.wfSignInputStore;
        updateParams[VariableKeys.FORWARD_SIGN_HANDWRITTEN+"_datasAndUrls"] = getVariableMapVal(VariableKeys.SIGN_HANDWRITTEN+"_datasAndUrls", {})
        batchControlVariableMap(updateParams);
    }
    return true;
}

//remark client info
export const getClientInfo = () => {
    const ua = Tools.mobileDetect().getUaInfo();
    const {isEmobile, mobile, os} = ua;
    const prefix = "<br/><br/><span style='font-size:11px;color:#666;'>";
    let remarkClientInfo = "";
    if (isEmobile) {
        let clienttype = mobile;
        if (os == 'AndroidOS') {
            clienttype = 'Android';
        }
        remarkClientInfo = `${prefix}${getLabel(31505, '来自')}${clienttype}${getLabel(108, ' 客户端 ')}</span>`;
        } else  {
            remarkClientInfo = `${prefix}${getLabel(31505, '来自')}Web${getLabel(31506, '手机版')}</span>`;
        }
    return remarkClientInfo;
}

export const getClientTypeInfo = () => {
    const ua = Tools.mobileDetect().getUaInfo();
    const {isEmobile, mobile, os} = ua;
    let clienttype = "a";
    if(isEmobile) {
        if (os == 'AndroidOS') {
            clienttype = "b";
        } else {
            clienttype = "c";
        }
    } else {
        const userAgent = Tools.ua;
        const {browser} = userAgent;
        if('Wechat' == browser) {
            clienttype = "e";
        } else if ('DingTalk' == browser) {
            clienttype = "f";
        }
    }
    return clienttype;
}

//获取客户端类型
export const getClientType = () => {
    const ua = Tools.mobileDetect().getUaInfo();
    const {isEmobile, mobile, os} = ua;
    let clienttype = 'Webclient';
    if (isEmobile) {
        clienttype = mobile;
        if (os == 'AndroidOS') {
            clienttype = 'Android';
        }
    }
    return clienttype;
}

/**
 * 计算底部btn高度
 * @return {string}
 */
export const calcReqMainPaadingBottom = () => {
    const {showBottomBtn = false} = base.allStores.wfOperateStore;
    const clienttype = getClientType();
    const themeVars = window.getThemeVars();
    const {hd = 1} = themeVars;
    let paddingBottom = '0px';
    if ((clienttype == 'Webclient' || !EmSDK.judgeApiSupport('showBottomToolBar')) && showBottomBtn) {
        paddingBottom = `${hd * 45}px`;
    }
    return paddingBottom;
}

//自动缩小图片
export const signImgResize = (_this) => {
    var innerWidth = window.innerWidth || (window.document.documentElement.clientWidth || window.document.body.clientWidth);
    var imgWidth = jQuery(_this).width();
    var imgHeight = jQuery(_this).height();
    var iframeWidth = window.innerWidth * 0.25;
    if (imgWidth >= iframeWidth) {
        var variable = imgWidth / iframeWidth;
        var variableWidth = imgWidth / variable;
        var variableHeight = imgHeight / variable;
        if (variableHeight >= 250) {
            var coefficient = variableHeight / 250;
            var coefficientWidth = variableWidth / coefficient;
            var coefficientHeight = variableHeight / coefficient;
            jQuery(_this).width(coefficientWidth);
            jQuery(_this).height(coefficientHeight);
        } else {
            jQuery(_this).width(variableWidth);
            jQuery(_this).height(variableHeight);
        }
    } else {
        if (imgHeight >= 250) {
            var coefficient = imgHeight / 250;
            var coefficientWidth = imgWidth / coefficient;
            var coefficientHeight = imgHeight / coefficient;
            jQuery(_this).width(coefficientWidth);
            jQuery(_this).height(coefficientHeight);
        } else {
            jQuery(_this).width(imgWidth);
            jQuery(_this).height(imgHeight);
        }
    }
}
//附件上传控制底部按钮是否可点击
export const onUploading = (type,comfrom) => {
    const {controlVariableMap} = base.allStores.wfSignInputStore;
    const fileUploading = getVariableMapVal(VariableKeys.SIGN_FILE_UPLOADING,false);
    if (type == 'uploading' && !fileUploading) {
        EmSDK.judgeApiSupport('userInteractionDisabled') && EmSDK.emClient.userInteractionDisabled({});
        controlVariableMap(VariableKeys.SIGN_FILE_UPLOADING,true);
    } else if (type == 'uploaded' && fileUploading) {
        EmSDK.judgeApiSupport('userInteractionEnabled') && EmSDK.emClient.userInteractionEnabled({});
        controlVariableMap(VariableKeys.SIGN_FILE_UPLOADING,false);
    }
}

export const quoteContentRemoveHtmlUtil = (str) => {
    let hea = str.substr(0, str.indexOf("<div _quotoContent='true'"));
    str = str.substr(str.indexOf("<div _quotoContent='true'"));
    let pic = `[${getLabel(528760 , '图片')}]`;
    str = str.replace(/<img.*?>/g, pic);
    str = str.replace(/<[^>]*>|<\/[^>]*>/gm, "")
    str = str.replace(/\r|\n|\\s/gm, "");
    str = `<div class='remark-quote'>${str}</div>`;
    str = hea + str + "</div>";
    return str;
}

/**
 * 转发选人title
 * @return {string}
 */
export const getForwardTitle = () => {
    const {fowardSubmitParams = {}, isForwad} =  base.allStores.wfSignInputStore;
    const {wfOperateStore} = base;
    const {markInfo = {}} = wfOperateStore;
    const {forwardflag = '1'} = fowardSubmitParams;

    //自定义按钮信息
    const {customBtnInfo = {}} = markInfo;
    const {btnNameInfo = {}} = customBtnInfo;
    let _actionName = btnNameInfo[forwardflag] || '';


    let actionName = getLabel(6011,'转发');
    if (forwardflag == '2') actionName = getLabel(82578,'意见征询');
    if (forwardflag == '3') actionName = getLabel(23745,'转办');
    if (forwardflag == '4') actionName = getLabel(23028,'传阅');
    if (forwardflag == '5') actionName = getLabel(507272,'征询转办');
    if(_actionName.length > 0){
        actionName = _actionName;
    }
   
    return `${getLabel(18214,'请选择')}${actionName}${getLabel(15525,'接收人')}`;
}

export const signPreViewImg = (_this) => {
    window.preViewImg(jQuery(_this));
}

export const loadMoreSign = () => {
    const {wfSignListStore} = base.allStores
    const {queryLogParams, totalCount, loglist = [], loading} = wfSignListStore;
    const {tabKey} = base.wfGlobalStore;
    if (totalCount > loglist.length && !loading) {
        if (tabKey === 'layout') {
            window.scrollEndEvent(window.jQuery('.wf-req-content')[0], function () {
                const {pgnumber} = queryLogParams;
                wfSignListStore.initDatas({pgnumber: pgnumber + 1}, true);
            }, 0);
        } else if (tabKey === 'signlist') {
            window.scrollEndEvent(window.jQuery('.wf-signList-scrollContent')[0], function () {
                const {pgnumber} = queryLogParams;
                wfSignListStore.initDatas({pgnumber: pgnumber + 1}, true);
            }, 0);
        }
    }
}

//停止播放中的语音
export const stopPlayingAudio = () => {
    const {variableMap} = base.allStores.wfSignInputStore;
    if(variableMap.has('currentAudioDOM')){
        let currentAudioDOM = variableMap.get('currentAudioDOM');
        if(currentAudioDOM){
            currentAudioDOM.pause();
        }
    }
}

//req 组件卸载前处理的事情
export const beforeReqComUninstall = () => {
    stopPlayingAudio();
}

export const convertSpecialChar = (str,isSetInnerHtml = false) =>{
    str = str.toString();
    if(!isSetInnerHtml) {
        str = str.replace(/<br>/ig, "\n");
    }
    str = str.replace(/&nbsp;/ig, " ");
    str = str.replace(/&lt;/ig, "<");
    str = str.replace(/&gt;/ig, ">");
    str = str.replace(/&quot;/ig, "\"");
    str = str.replace(/&amp;/ig, "&");
    return str;
}

  //处理意见
  export const getRemarkHtml = (log_remarkHtml = '', convertImg=true,calImgWidth=true) => {
    let reg = /href=\"\/spa\/document\/index.jsp\?.*?\"/g;
    let docs = log_remarkHtml.match(reg);
    let remarkHtmlTemp = log_remarkHtml;
    docs && docs.map((item) => {
        if (/\&(amp;){0,1}id=(\d*?)\&/g.test(item)) {
            let docid = RegExp.$2;
            remarkHtmlTemp = remarkHtmlTemp.replace(item, `onclick="window.showFormDoc(${docid},{})"`);
        }
    })
    let reg2 = /href=\"\/workflow\/request\/ViewRequestForwardSPA.jsp.*?\"/g;
    let reqs = log_remarkHtml.match(reg2);
    reqs && reqs.map((v) => {
        if (/\&(amp;){0,1}requestid=(\d*?)\&/g.test(v)) {
            let requestid = RegExp.$2;
            remarkHtmlTemp = remarkHtmlTemp.replace(v, `onclick="window.showFormReq(${requestid},{})"`);
        }
    })

    //跳转人力资源卡片
    let reg3 = /href=\"\/hrm\/HrmTab.jsp\?.*?\"/g;
    let ats = log_remarkHtml.match(reg3);
    ats && ats.map((v) => {
        if (/\&(amp;){0,1}id=(\d*?)\"/g.test(v)) {
            let id = RegExp.$2;
            remarkHtmlTemp = remarkHtmlTemp.replace(v, `onclick="window.showHoverWindow('/spa/hrm/static4mobile/index.html#/resourceInfo/${id}','/req')"`);
        }
    })

    if(convertImg){
        let reg4 = /<img.*?(\/>|<\/img>|>)/g;
        let images = remarkHtmlTemp.match(reg4);
        images && images.map((v) => {
            let oldclass = "";
            if(/class=(\"|\')(.*?)(\"|\')/g.test(v)) { 
                oldclass = RegExp.$2;
            }
            if (oldclass != 'signatureImg') {
                 //为img添加同一处理
                 if(calImgWidth){
                    let _v = v.replace(/<img/g, `<img onload='window.signImgResize(this)' onClick='window.signPreViewImg(this)' img-key="signlist" class='formImgPlay ${oldclass}'`);
                    remarkHtmlTemp = remarkHtmlTemp.replace(v, _v);
                }else{
                    let _v = v.replace(/<img/g, `<img onClick='window.signPreViewImg(this)' img-key="signlist" class='formImgPlay ${oldclass}'`);
                    remarkHtmlTemp = remarkHtmlTemp.replace(v, _v);
                }
            }
        })
    }

    //附件上传字段  <a\s+href="(.*)"\s+title="(.*)"\s*>(.*)<\s*/a>
    let reg5 =  /href=\"javascript[:]void[(]0[)]\;\"\s+onclick=\"(parent.openFullWindowHaveBar)[(]\'\/spa\/document\/index.jsp\?.*?[)]\"/g;
    let files = remarkHtmlTemp.match(reg5);
    files && files.map((item) => {
        if (/\&(amp;){0,1}id=(\d*?)\&/g.test(item)) {
            let docid = RegExp.$2;
            remarkHtmlTemp = remarkHtmlTemp.replace(item, `onclick="window.showFormDoc(${docid},{},'/req')"`);
        }
    })

    //超链接
    let reg6 = /href=(\"([^<>"\']*)\"|\'([^<>"\']*)\')/gi;
    let a_links = remarkHtmlTemp.match(reg6);
    a_links&&a_links.map(item=>{
        if(/\"([^<>"\']*)\"|\'([^<>"\']*)\'/g.test(item)){
            let url = RegExp.$1 || RegExp.$2;
            remarkHtmlTemp = remarkHtmlTemp.replace(item, `onclick="window.showHoverWindow('${url}','/req')"`);
        }
    })

    //表单内签字意见中的附件、文档
    let reg7 = /onclick=\"addDocReadTag[(][0-9]*[)]\;openFullWindowHaveBar[(](\'\/spa\/document\/index.jsp\?.*?\')[)]\"/g;
    let remark_docs = remarkHtmlTemp.match(reg7);
    remark_docs && remark_docs.map(item=>{
        if (/id=(\d*?)\&/g.test(item)) {
            let docid = RegExp.$1;
            remarkHtmlTemp = remarkHtmlTemp.replace(item, `onclick="window.showFormDoc(${docid},{})"`);
        }
    })
    //表单内签字意见中的流程
    let reg8 = /onclick=\"openFullWindowHaveBar[(](\'\/workflow\/request\/ViewRequestForwardSPA.jsp.*?\')[)]\"/g;
    let remark_reqs = remarkHtmlTemp.match(reg8);
    remark_reqs && remark_reqs.map((v) => {
        if (/requestid=(\d*?)\&/g.test(v)) {
            let requestid = RegExp.$1;
            remarkHtmlTemp = remarkHtmlTemp.replace(v, `onclick="window.showFormReq(${requestid},{})"`);
        }
    })
    
    //remarkHtmlTemp = convertSpecialChar(remarkHtmlTemp,true);
    return remarkHtmlTemp;
}

//验证意见是否必填
export const verifyRemarkMustInput = (src = '',actionType = '',needCheck=false,isaffirmanceSrc = 'submit') => {
    const { markInfo = {},rightMenu = {} } = base.wfOperateStore;
    const { signMustInputTypes = []} = markInfo;
    if('save' === src) {
        if(actionType === 'requestOperation') {
            if(needCheck) {
                return signMustInputTypes.indexOf(isaffirmanceSrc) > -1;
            }
            return false;
        } else {
            const {remarkOperationType = ''} = rightMenu;
            return signMustInputTypes.indexOf(remarkOperationType) > -1
        }
    }
    return signMustInputTypes.indexOf(src) > -1;
}


window.signPreViewImg = signPreViewImg;
window.signImgResize = signImgResize;